function FirstAssistant() {
	/* this is the creator function for your scene assistant object. It will be passed all the 
	   additional parameters (after the scene name) that were passed to pushScene. The reference
	   to the scene controller (this.controller) has not be established yet, so any initialization
	   that needs the scene controller should be done in the setup function below. */
	document.getElementById("mainBody").style.backgroundImage = "url(images/background.png)";
}

FirstAssistant.prototype.setup = function() {
try{	
	this.switchMenuModel = {
                visible: true,
                items: [{
                        items: [
                                { icon: 'back', command: 'extra', label: $L('Back')},
                                { label: "Main", width: 200 },
                                { icon: 'forward', command: 'extra', label: $L('Fwd')}
                               ]
                        }]
        };
		//disabled for now
        //this.controller.setupWidget(Mojo.Menu.viewMenu, { spacerHeight: 50, menuClass:'no-fade' }, this.switchMenuModel);	
	
	this.myTrack = [];
	this.myRoute = [];
	this.myGPSCollection = new gpsCollection();
	this.myDisplay = new gpsDisplay();
	this.myUnits = new unitsObject();
	this.myUnits.setUnits(1);//2 for metric, anying else is standard
	
	
	this.myDisplay.resetGPSDisplay();
	 
	//this.measurementSystem = "Standard";// Other option is Metric
	//this.setMeasurementSystem(this.measurementSystem);
	
	this.timecount=0;
	this.starttimes;
	this.seconds;
	this.minutes;
	this.hours;
	this.pausestart=0;
	this.pausetime=0;
	this.elapsedTotal;
	
	this.start=0;
	this.run=0;

	
	// Variables to caclculate pace
	
	this.pacecounter;
	this.pacedistance;
	this.pacetime;
	this.paceinterval=30; // how many coordinates to average pace over
	this.paceupdate=5; // how frequently to update pace
	this.pacecount=0;
		
	this.count=1;
	this.distance=0;
	this.travel=0;
	this.pace;
	this.avspeed;	
	
	this.StartButtonModel = {
		buttonLabel : 'Find Location',
		buttonClass : 'affirmative',
		disable : false
	};
	
	this.StartButtonAtt = {}
	
	this.StopModel = {
		buttonLabel : 'Pause',
		disabled : true,
	};
	
	this.StopAtt = {
	};
		
	this.toggleatts ={
		property: 'togglestate',
		trueLabel: 'On',
		falseLabel: 'Off'
	};
	
	this.togglemodel ={
		togglestate: false
	};
	
	this.listmodel ={
		open: false
	};
	
	this.LoadMapAtt = {
	};
	this.EmailGPXAtt = {
	};
	this.EmailCoordsAtt = {
	};
	
	this.LoadMapModel = {
		buttonLabel : 'Show Map',
		disable : false
	};
	this.EmailGPXModel = {
		buttonLabel : 'Email GPX',
		disable : false
	}
	this.EmailCoordsModel = {
		buttonLabel : 'Email Coodinates',
		disable : false
	}
		
	this.controller.setupWidget('StartButton',this.StartButtonAtt,this.StartButtonModel);
	this.controller.listen(this.controller.get('StartButton'),Mojo.Event.tap, this.handleStartButtonPressed.bind(this));
	
	this.controller.setupWidget('Stop',this.StopAtt,this.StopModel);
	this.controller.listen(this.controller.get('Stop'),Mojo.Event.tap, this.handleStopPressed.bind(this));
	
	this.controller.setupWidget("toggle1",this.toggleatts,this.togglemodel);
	Mojo.Event.listen(this.controller.get('toggle1'),Mojo.Event.propertyChange,this.togglechange.bindAsEventListener(this));

	this.controller.setupWidget("hiddenlist",{},this.listmodel);
	this.drawer = this.controller.get('hiddenlist');
	
	this.controller.setupWidget('LoadMap',this.LoadMapAtt,this.LoadMapModel)
	Mojo.Event.listen($("LoadMap"), "click", this.loadmap.bindAsEventListener(this));
	
	this.controller.setupWidget('EmailGPX',this.EmailGPXAtt,this.EmailGPXModel)
	Mojo.Event.listen($("EmailGPX"), "click", this.emailgpx.bindAsEventListener(this));
	
	this.controller.setupWidget('EmailCoords',this.EmailCoordsAtt,this.EmailCoordsModel)
	Mojo.Event.listen($("EmailCoords"), "click", this.emailcoords.bindAsEventListener(this));
	
	this.emailSequence1 = 0;
	this.emailSequence2 = 0;
	
	Mojo.Event.listen($("refreshes"), Mojo.Event.tap, this.refreshesTap.bindAsEventListener(this));
	Mojo.Event.listen($("horiz"), Mojo.Event.tap, this.horizTap.bindAsEventListener(this));
	Mojo.Event.listen($("vert"), Mojo.Event.tap, this.vertTap.bindAsEventListener(this));
	}
catch(e){
	$('error_area-to-update').update(e.message);
 
}	
}

FirstAssistant.prototype.refreshesTap = function(){this.emailSequence1 = 1;}
FirstAssistant.prototype.horizTap = function(){
	if (this.emailSequence1 == 1){
		this.emailSequence2 = 1;
	} else {
		this.emailSequence1 = 0;
	}
}
FirstAssistant.prototype.vertTap = function(){
	if (this.emailSequence1 == 1 && this.emailSequence2 == 1){
		$('EmailCoords').style.display = "";
	} else {
		this.emailSequence1 = 0;
		this.emailSequence2 = 0;
	}
}
FirstAssistant.prototype.ExposeEmailGPX = function(){
	$('EmailGPX').style.display = "";
}

/*
FirstAssistant.prototype.setMeasurementSystem = function(measureSys){
	if (measureSys == "Metric") {
		this.longDist = 1;
		this.shortDist = 1;
		this.speedUnit = 1;
		this.velocityUnit = 3.6;//meters per sec to KPH
	}
	else {
		this.longDist = 0.62137;//km to miles
		this.shortDist = 3.28;//meters to feet
		this.speedUnit = 0.62137;//KPH to MPH
		this.velocityUnit = 2.237;//meters per sec to MPH
	}
}*/

FirstAssistant.prototype.togglechange = function(event){
	this.drawer.mojo.setOpenState(!this.drawer.mojo.getOpenState());
}


FirstAssistant.prototype.handleStopPressed = function () {
	
	// Currently tracking, pause requested
	if (this.run == 1) {
		
		// change start button to resume
		this.StartButtonModel.disabled = false;
		this.StartButtonModel.buttonLabel = "Resume"
		this.controller.modelChanged(this.StartButtonModel)
		this.ExposeEmailGPX();
		
		// run = 3 means pause
		this.run = 3;
		
		// change stop button to reset
		this.StopModel.disabled = false;
		this.StopModel.buttonClass = 'negative';
		this.StopModel.buttonLabel = "Reset"
		this.controller.modelChanged(this.StopModel)
		
		// start pause time
		this.pausestart=(new Date).getTime()
		
		//stop tracking and stop activity
		this.trackingHandle.cancel();
		this.activityEnd();
	}
	// Currently paused, reset requested
	else if (this.run==3){
		
		// run = 4 means reset
		this.run=4
		this.start=0
		
		// change start button to "find location"
		this.StartButtonModel.disabled = false;
		this.StartButtonModel.buttonLabel = "Find Location"
		this.controller.modelChanged(this.StartButtonModel)
		
		//reset time
		$('time').innerHTML = "0:00:00"
	}
}


FirstAssistant.prototype.handleStartButtonPressed = function(){
	
	// Find Location
	if (this.start == 0) {
		
		// Get satellites locked on
		if (this.run != 4){
				this.startTracking()
		}
		
		// change start button text
		this.StartButtonModel.disabled = true;
		this.StartButtonModel.buttonLabel = "Searching..."
		
		this.controller.modelChanged(this.StartButtonModel);
		
		// initialize parameters
		this.count=1;
		this.run=0;
		this.timeon=0;
		this.pausetime=0;
	}
	
	// Start Tracking
	if (this.start==1){
		
		//change text and state of start button
		this.StartButtonModel.disabled = true;
		this.StartButtonModel.buttonLabel = "Tracking";
		this.controller.modelChanged(this.StartButtonModel);
		
		// run = 1 for tracking active
		this.run=1;
		
		// set stop button to pause
		this.StopModel.buttonLabel= "Pause";
		this.StopModel.disabled = false;
		this.StopModel.buttonClass = 'primary';
		this.controller.modelChanged(this.StopModel);
		
		// If this is a resume from a pause, then set pause time
		if (this.pausestart != 0) {
			this.pauseend = (new Date).getTime()
			this.pausetime = this.pausetime + this.pauseend - this.pausestart 
			this.pausestart=0;
		}
		
		// If this is a first time start, then set start time and initiate tracking
		if (this.timeon == 0) {
			this.starttime = (new Date).getTime()
			this.pausetime=0
			
			// calls this.timer() every 1000 ms to update time
			window.setInterval(this.timer.bind(this), 1000);
			this.timeon=1;
		}
	}	
}
	
FirstAssistant.prototype.startTracking = function(){
	// Initializes location based services
	this.trackingHandle = this.controller.serviceRequest('palm://com.palm.location', {
			method : 'startTracking',
	        parameters: {
				accuracy: 1, 
				maximumAge: 1,
				responseTime: 1,
				subscribe: true
			},
	        onSuccess: this.handleServiceResponse.bind(this),
	        onFailure: this.handleServiceResponseError.bind(this)
	    });
		this.activityStart();
}
FirstAssistant.prototype.activityStart = function (){
	appID = 'com.fitTrack.0.7.start.Activity';
	this.controller.serviceRequest('palm://com.palm.power/com/palm/power', {
		method: 'activityStart',	
		parameters: {	 	
			id: appID, 
			duration_ms: '400000'
		},
		onSuccess: this.activitySuccess.bind(this),
		onFailure: this.activityFailure.bind(this)
	});
}
FirstAssistant.prototype.activityEnd = function (){
	appID = 'com.fitTrack.0.7.start.Activity';
	this.controller.serviceRequest('palm://com.palm.power/com/palm/power', {
		method: 'activityEnd',	
		parameters: {	 	
			id: appID
		},	
		onSuccess: this.activitySuccess.bind(this),
		onFailure: this.activityFailure.bind(this)
	});
}
FirstAssistant.prototype.activitySuccess = function(){
	//$('error_area-to-update').update('screen timeout success')
}
FirstAssistant.prototype.activityFailure = function(){
	//$('error_area-to-update').update('screen timeout failed')
}

FirstAssistant.prototype.timer = function (){
	
	// Currently tracking
	if (this.run==1){
		
		// Get timestamp;
		this.newtime=(new Date).getTime();
		this.pausetime; 
		
		this.elapsedTotal = (this.newtime-this.starttime-this.pausetime);
		
		// Format time for display
		this.seconds=Math.floor((this.newtime-this.starttime-this.pausetime)/1000);
		this.minutes=Math.floor((this.newtime-this.starttime-this.pausetime)/60000);
		//reset activity every 14 minutes
		if (this.seconds % 300 == 0 && this.seconds != 0){
			
			
			var msg = {messageText: "Min: " + this.minutes + " Distance: " + this.myGPSCollection.totalDistance()};	
			Mojo.Controller.getAppController().showBanner(msg, "","Information");
			this.activityEnd();
			this.activityStart();
				
			//this.trackingHandle.cancel();
			//this.startTracking();
		}
		
		this.hours=Math.floor((this.newtime-this.starttime-this.pausetime)/3600000);
		this.hourstotal=(this.newtime-this.starttime-this.pausetime)/3600000; 
		
		// Format seconds
		if (this.seconds>=60){this.seconds=this.seconds-this.minutes*60}
		if (this.seconds<10){this.seconds= "0" + this.seconds}
		
		// Format minutes
		if (this.minutes>=60){this.minutes=this.minutes-this.hours*60}
		if (this.minutes<10){this.minutes= "0" + this.minutes}
		
		// Add colon to minutes
		this.minutes = this.minutes + ":"
		
		// Format hours
		if (this.hours<1){this.hour="00"}
		if (this.hours<10){this.hour= "0" + this.hour}
		
		// Add colon to hours
		this.hours = this.hours + ":"
		
		// Set time on display
		$('time').innerHTML = this.hours+this.minutes + this.seconds
	}
	
	// Currently paused
	if (this.run==3){
		$('time').innerHTML = this.hours+this.minutes + this.seconds
	}
	
	// Currently reset
	if (this.run==4){
		$('time').innerHTML = '0:00:00'
	}
}


FirstAssistant.prototype.handleServiceResponse = function(event){
try{
	
	//this.myGPSCollection.simulate();
	this.myGPSCollection.storeEvent(event);
	if (this.run == 0){
		this.myGPSCollection.setTally(false);
	}
	else{
		this.myGPSCollection.setTally(true);
	}
	
	
	
	success = this.myGPSCollection.registerEvent(this.myUnits, this.elapsedTotal);
	
	
	if (success) {
		//$('error_area-to-update').innerHTML += this.myGPSCollection.GPSCount;	
		currentNode = this.myGPSCollection.currentNode();
		
		if (this.run == 0) {
			if (this.count == 1) {
				this.StartButtonModel.buttonLabel = "Please Wait ..."
				this.StartButtonModel.buttonClass = 'affirmative';
				$('GPS_error_area-to-update').update("");
				this.controller.modelChanged(this.StartButtonModel);
				this.count++;
			}
			else {
				this.start = 1
				this.StartButtonModel.buttonLabel = "Start"
				this.StartButtonModel.buttonClass = 'affirmative';
				$('GPS_error_area-to-update').update("");
				this.StartButtonModel.disabled = false;
				this.controller.modelChanged(this.StartButtonModel);
				this.timeon = 0;
			}			
		}
		else 
			if (this.run == 1) {
				this.count++;
				this.StartButtonModel.buttonLabel = "Tracking"
				this.StartButtonModel.buttonClass = 'affirmative ';
				this.controller.modelChanged(this.StartButtonModel);
				$('GPS_error_area-to-update').update("");
				
				
				//Call function to start distance tally
				
				
				
				//myDate = new Date(event.timestamp);
				//$('error_area-to-update').update(myDate.toUTCString());	
				//$('error_area-to-update').update(this.myGPSCollection.getLat());
				
				
				//call function to deal with dispay
				
				//this.myDisplay.setGPSDisplay(currentNode,this.velocityUnit, this.myGPSCollection.GPSCount);
				this.myDisplay.show(this.myGPSCollection, this.myUnits);
			}
		
	}
	else{
		if(this.myGPSCollection.GPSCount > 7){
			$('GPS_error_area-to-update').update("The device is having trouble finding a good signal.");
			this.StartButtonModel.buttonLabel = "Reading GPS ... ";
			this.StartButtonModel.buttonClass = 'negative';
			this.controller.modelChanged(this.StartButtonModel);
		}
	}
	
}
catch(e){
	$('error_area-to-update').innerHTML = " :main<br>";
	$('error_area-to-update').innerHTML +=e.message;
 	
}
}


FirstAssistant.prototype.handleServiceResponseError = function(event){
	/* put in event handlers here that should only be in effect when this scene is active. For
	 example, key handlers that are observing the document */
	this.getButton = this.controller.get('StartButton');
	this.getButton.mojo.deactivate();
	$('error_area-to-update').update("Get Location Error:" + Object.toJSON(event));
}

FirstAssistant.prototype.loadmap = function (){
 if (this.myRoute.length > 1) {
		this.controller.serviceRequest('palm://com.palm.applicationManager', {
		    method: 'launch',
		    parameters: {
		        id:"com.palm.app.maps",
		        params:{query:"Your Location@"+this.myRoute[this.myRoute.length-1].latitude+","+this.myRoute[this.myRoute.length-1].longitude}
		        //params:{"query":this.locationaddress}
		    }
		});
	} else {
		$('error_area-to-update').update("No location set. Start Tracking! ");
	}
}
FirstAssistant.prototype.emailgpx = function(){
try{	
	//var coords = "latitude,longitude,altitude,errorCode,heading,horizAccuracy,vertAccuracy,velocity,velocitysmooth,timestamp,timer,distanceMeasured,speedMeasured,travelMeasured,travelVertical,deltaAlt<br/>";
	/*for (var i = 0; i < this.myTrack.length; i++) {
		coords += this.myTrack[i].gpsToString();
	}*/
	var coords = this.myGPSCollection.compileGPX();
	
	this.controller.serviceRequest(
	'palm://com.palm.applicationManager',
	{method: 'open',
	 parameters: {
		id: 'com.palm.app.email',
		params: {summary: 'FitTrack GPX',
				text: coords}
				}
	}
	);
}
catch(e){
	$('error_area-to-update').innerHTML = " :GPX<br>";
	$('error_area-to-update').innerHTML +=e.message;
 	
}	
}

FirstAssistant.prototype.emailcoords = function(){
try{	
	var coords = "latitude,longitude,altitude,errorCode,heading,horizAccuracy,vertAccuracy,velocity,velocitysmooth,timestamp,distanceMeasured,speedMeasured,travelMeasured,travelVertical,deltaAlt<br/>";
	for (var i = 0; i < this.myGPSCollection.cleanGPSData.length; i++) {
		coords += this.myGPSCollection.cleanGPSData[i].gpsToString();
	}	
	this.controller.serviceRequest(
	'palm://com.palm.applicationManager',
	{method: 'open',
	 parameters: {
		id: 'com.palm.app.email',
		params: {summary: 'FitTrack GPX',
				text: coords}
				}
	}
	);
}
catch(e){
	$('error_area-to-update').innerHTML = " :email<br>";
	$('error_area-to-update').innerHTML +=e.message;
 	
}	
}
	
	FirstAssistant.prototype.activate = function(){
		/*if (this.controller.stageController.setWindowOrientation)
		 
		 
		 {
		 
		 
		 this.controller.stageController.setWindowOrientation("free");
		 
		 
		 }*/
	}

	
	FirstAssistant.prototype.deactivate = function(event){
	
		/* remove any event handlers you added in activate and do any other cleanup that should happen before
		
		 this scene is popped or another scene is pushed on top */
		
	}
	
	FirstAssistant.prototype.cleanup = function(event){
		this.myGPSCollection = "";
		/* this function should do any cleanup needed before the scene is destroyed as 
		 a result of being popped off the scene stack */
	}
	
	FirstAssistant.prototype.activitySuccess = function(event){
	}
	
	FirstAssistant.prototype.activityFailure = function(event){
	}
	



